import json

import jwt
from django.shortcuts import render

# Create your views here.

from .models import User
from django.http import JsonResponse
from django.forms import model_to_dict
from datetime import datetime,timedelta
from django.core.paginator import Paginator
from django.views.decorators.csrf import csrf_exempt
from .models import productList
from .models import Product
from .models import orderForm
#判断用户名是否为空
def is_exf(c):
    return c is None or str(c).strip()==''
#登录
@csrf_exempt
def login(request):
    if request.method=='POST':
        data=json.loads(request.body)
        username=data.get('username')
        password=data.get('password')

        if is_exf(username) or is_exf(password):
            return JsonResponse({'msg':'用户名或者密码不能为空'})

        if User.objects.filter(username=username).exists()==False:
            return JsonResponse({'msg':'用户名不存在'},status=400)

        user=User.objects.get(username=username)

        if user.password!=password:
            return JsonResponse({"msg":'密码错误'},status=400)

        p={"username":user.username,'password':user.password}
        mi='123456'
        token=jwt.encode(p,mi)
        return JsonResponse({'msg':'登录成功','token':token},status=200)

#商品分类查询接口（给前端提供下拉列表数据）
@csrf_exempt
def goodsFen(request):
    all_data=productList.objects.all()
    list=[]

    for i in all_data:
        list.append(model_to_dict(i))

    return JsonResponse({'msg':'查询成功','data':list})


#查询商品-分页、条件筛选（对应前端）
@csrf_exempt
def getlist(request):
    if request.method=='GET':
        all_data=Product.objects.all()
        total=len(all_data)
        #分页加载
        paze=request.GET.get('paze',1)
        size=request.GET.get('size')or 5
        productName=request.GET.get('productName','')
        list=[]
        #商品分类
        id=request.GET.get('id')

        if productName:
            all_data=all_data.filter(productName=productName)

        if id:                       #加载商品分类表数据)筛选
            all_data=all_data.filter(productCategory_id=id)
        data=Paginator(all_data,size)
        all_data=data.get_page(paze)

        for i in all_data:
            list.append(model_to_dict(i))

        return JsonResponse({'msg':'查询成功','data':list,'total':total})

    #新增
    elif request.method=='POST':
        data=json.loads(request.body)
        productName=data.get('productName')
        productCategory_id=data.get('productCategory_id')
        thePriceOfTheCommodity=data.get('thePriceOfTheCommodity')
        productInventory=data.get('productInventory')
        creationTim=data.get('creationTim')

        jiegou=Product.objects.create(
            productName=productName,
            productCategory_id=productCategory_id,
            thePriceOfTheCommodity=thePriceOfTheCommodity,
            productInventory=productInventory,
            creationTim=creationTim
        )
        data1=model_to_dict(jiegou)
        return JsonResponse({'msg':'增加成功','data':data1})

#更新商品时创建/修改时间初始化系统当前时间
@csrf_exempt
def updata(request,id):
    data=Product.objects.get(id=id)
    if request.method=='PUT':
        data1=json.loads(request.body)
        data.productName=data1.get('productName')
        data.productCategory_id=data1.get('productCategory_id')
        data.thePriceOfTheCommodity=data1.get('thePriceOfTheCommodity')
        data.productInventory=data1.get('productInventory')
        # data.creationTim=data1.get('creationTim')
        data.save()
        data2=model_to_dict(data)
        return JsonResponse({'msg':'修改成功','data':data2},status=200)

    elif request.method=='DELETE':
        if orderForm.objects.filter(goods_id=id).exists()==True:
            return JsonResponse({'msg':'该商品有关联,无法删除'})
        else:
            data.delete()
            return JsonResponse({'msg':'删除成功'})

#④订单创建、查询接口（多表关联）
@csrf_exempt
def add(request):
    if request.method=='POST':
        data=json.loads(request.body)
        orderQuantity=data.get('orderQuantity')
        theAmountOfTheOrder=data.get('theAmountOfTheOrder')
        customerCharacters=data.get('customerCharacters')
        creationTim=data.get('creationTim')
        date=data.get('date')
        goods_id=data.get('goods_id')
        user_id_id=data.get('user_id_id')

        jiegou=orderForm.objects.create(
            orderQuantity=orderQuantity,
            theAmountOfTheOrder=theAmountOfTheOrder,
            customerCharacters=customerCharacters,
            # creationTim=creationTim,
            # date=date,
            goods_id=goods_id,
            user_id_id=user_id_id
        )
        data1=model_to_dict(jiegou)
        #创建订单成功后，对应商品库存减少相应的数量 "我要用商品 ID 去查询 Product 对象"
        good=Product.objects.get(id=goods_id)
        good.productInventory=int(good.productInventory)-int(orderQuantity)
        good.save()
        return JsonResponse({'msg':'增加成功','data':data1})
    elif request.method=='GET':
        data=orderForm.objects.all()
        list=[]
        paze=request.GET.get('paze',1)
        size=request.GET.get('size') or 10
        productName=request.GET.get('productName','')
        if productName:
            goods_id = Product.objects.get(productName=productName).id
        #过滤出 goods_id 等于上一步查到的商品 ID 的订单。
        # 例如，如果商品 "手机" 的 ID 是 1001，
        # 就会筛选出所有 goods_id=1001 的订单
        if productName:
            data = data.filter(goods_id=goods_id)
        data1=Paginator(data,size)
        data=data1.get_page(paze)
        for i in data:
            list.append(model_to_dict(i))

        return JsonResponse({'msg':'查询成功','data':list})




